package com.starmark.gateway.springcloud.provider.exception;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.starmark.gateway.springcloud.provider.response.ErrorResponseData;
import com.starmark.gateway.springcloud.provider.response.Response;
import io.netty.channel.ConnectTimeoutException;
import lombok.extern.slf4j.Slf4j;

import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;

@Slf4j
@RestControllerAdvice
public class GateWayExceptionHandlerAdvice {

    @ExceptionHandler(value = {ResponseStatusException.class})
    public Response handle(ResponseStatusException ex) {
        log.error("response status exception:{}", ex);
        return ErrorResponseData.newInstance(SystemErrorType.GATEWAY_ERROR, ExceptionUtil.getMessage(ex));
    }

    @ExceptionHandler(value = {ConnectTimeoutException.class})
    public Response handle(ConnectTimeoutException ex) {
        log.error("connect timeout exception:{}", ex);
        return ErrorResponseData.newInstance(SystemErrorType.GATEWAY_CONNECT_TIME_OUT, ExceptionUtil.getMessage(ex));
    }
    @ExceptionHandler(value = {BaseException.class})
    public Response handle(BaseException baseException) {
        log.error("BaseException:{}", baseException.getMessage());
        return ErrorResponseData.newInstance(baseException.getErrorType(), baseException.getMessage());
    }

    @ExceptionHandler(value = {NotFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Response handle(NotFoundException ex) {
        log.error("not found exception:{}", ex);
        return ErrorResponseData.newInstance(SystemErrorType.GATEWAY_NOT_FOUND_SERVICE, ExceptionUtil.getMessage(ex));
    }


    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handle(Exception ex) {
        log.error("exception:{}", ex.getMessage());
        return ErrorResponseData.newInstance(SystemErrorType.SYSTEM_ERROR, ExceptionUtil.getMessage(ex));
    }

    @ExceptionHandler(value = {Throwable.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handle(Throwable throwable) {
        log.error("Throwable:{}", throwable.getMessage());
        return ErrorResponseData.newInstance(SystemErrorType.SYSTEM_ERROR, ExceptionUtil.getMessage(throwable));
    }


}
